package cc.sunni.sell.controller;

import cc.sunni.sell.dto.OrderDto;
import cc.sunni.sell.entity.OrderDetail;
import cc.sunni.sell.form.OrderForm;
import cc.sunni.sell.service.OrderMasterService;
import cc.sunni.sell.service.WebSocket;
import cc.sunni.sell.utils.PageUtils;
import cc.sunni.sell.utils.Query;
import cc.sunni.sell.utils.R;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jl
 * @since 2021/1/18 21:56
 */
@RestController
@RequestMapping("/buyer/order")
public class BuyerOrderController {
    @Autowired
    private OrderMasterService orderMasterService;
    @Autowired
    private WebSocket webSocket;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public R create(@Validated @RequestBody OrderForm orderForm) {
        OrderDto orderDTO = new OrderDto();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        List<OrderDetail> orderDetailList = JSONUtil.toList(orderForm.getItems(), OrderDetail.class);
        orderDTO.setOrderDetailList(orderDetailList);
        String orderId = orderMasterService.create(orderDTO);

        // 发送websocket消息
        webSocket.sendMessage("您有新的订单啦", orderForm.getSellerId());
        return R.ok(orderId);
    }

    /**
     * 订单列表
     */
    @GetMapping("/list")
    public R list(@RequestParam("openid") String openid, @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map<String, Object> param = new HashMap<>();
        param.put(Query.PAGE_NO, page);
        param.put(Query.SIZE, size);
        param.put("openid", openid);
        PageUtils pageUtils = orderMasterService.queryPage(param);
        return R.ok(pageUtils.getList());
    }

    /**
     * 订单详情
     */
    @GetMapping("/detail")
    public R detail(@RequestParam String openid, @RequestParam String orderId) {
        OrderDto one = orderMasterService.findOne(orderId);
        return R.ok(one);
    }

    /**
     * 取消订单
     */
    @PostMapping("/cancel")
    public R cancel(@RequestParam String openid, @RequestParam String orderId) {
        OrderDto orderDto = orderMasterService.findOne(orderId);
        orderMasterService.cancel(orderDto);
        return R.ok();
    }
}
